package com.zys.sac.core.config;

import com.google.gson.Gson;
import com.zys.sac.core.constant.RequestStatus;
import com.zys.sac.core.exception.SacAuthorizationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created by zhongjunkai on 2022/3/11.
 */
@Component
public class UrlAccessDecisionManager implements AccessDecisionManager {

    @Autowired
    private Gson gson;

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        Set<String> ownAuthorities = authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toSet());
        for(ConfigAttribute configAttribute : configAttributes) {
            String role = configAttribute.getAttribute();
            //如果当前用户的角色中包含权限角色，表示该用户有相关的权限
            if(ownAuthorities.contains(role)) {
                return;
            }
        }
        throw new SacAuthorizationException(RequestStatus.UNAUTHORIZATION.getCode(), RequestStatus.UNAUTHORIZATION.getMsg());
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
